package com.ttg.web.service.Impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.handler.inter.IWriter;
import com.ttg.common.entities.BasePage;
import com.ttg.common.entities.BaseResult;
import com.ttg.common.entities.UserTokenInfo;
import com.ttg.common.enums.ErrorCodeEnums;
import com.ttg.common.enums.OperationTypeEnum;
import com.ttg.common.enums.ResultStatusEnum;
import com.ttg.common.enums.TagClassStatusEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.DateTimeUtil;
import com.ttg.common.utils.UserUtil;
import com.ttg.model.dto.TagClassDTO;
import com.ttg.model.dto.TagClassPageDTO;
import com.ttg.model.pojo.TagClass;
import com.ttg.model.vo.TagClassVO;
import com.ttg.web.dao.TagClassDao;
import com.ttg.web.service.TagClassService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/10/20 17:52
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Slf4j
@Service
public class TagClassServiceImpl implements TagClassService {

    @Autowired
    private TagClassDao tagClassDao;

    @Override
    public BasePage<TagClassVO> pagelist(TagClassPageDTO reqDto) {
        BasePage<TagClassVO> page = tagClassDao.pagelist(reqDto);
        return page;
    }

    @Override
    public BaseResult add(TagClassDTO reqDto) {
        //参数校验
        paramValid(reqDto,OperationTypeEnum.ADD);
        UserTokenInfo user = UserUtil.getUser();
        TagClass tagClass = new TagClass();
        tagClass.setClassName(reqDto.getClassName());
        tagClass.setClassDescription(reqDto.getClassDescription());
        tagClass.setClassChildList(0);
        tagClass.setClassType(reqDto.getClassType());
        if(reqDto.getClassLevel()==1){
            tagClass.setClassParentId(null);
        }else {
            //父级标签childlist加1
            TagClass parentClass = tagClassDao.getParentClass(reqDto.getClassParentId());
            if(parentClass==null){
                throw new BaseException("上级标签不存在，请检查");
            }
            Integer childList = parentClass.getClassChildList();
            parentClass.setClassChildList(childList+1);
            tagClassDao.saveOrUpdate(parentClass);
            tagClass.setClassParentId(reqDto.getClassParentId());
        }

        tagClass.setClassLevel(reqDto.getClassLevel());
        Integer sortNo = getSortNo(null,reqDto.getClassLevel());
        tagClass.setClassSortNo(sortNo);
        tagClass.setClassStatus(TagClassStatusEnum.ON.getValue());
        tagClass.setAddTime(LocalDateTime.now());
        tagClass.setAddId(user.getAdmId());
        tagClass.setUpdateTime(LocalDateTime.now());
        tagClassDao.save(tagClass);
        return BaseResult.success(ResultStatusEnum.SUCCESS);
    }

    @Override
    public BaseResult edit(TagClassDTO reqDto) {
        //参数校验
        paramValid(reqDto,OperationTypeEnum.UPDATE);
        TagClass old = tagClassDao.getById(reqDto.getClassId());
        if(old==null){
            throw new BaseException("标签不存在");
        }
        old.setClassName(reqDto.getClassName());
        old.setClassDescription(reqDto.getClassDescription());
        old.setClassStatus(reqDto.getClassStatus());
        old.setUpdateTime(LocalDateTime.now());
        old.setClassType(reqDto.getClassType());
        tagClassDao.updateById(old);
        return BaseResult.success(ResultStatusEnum.SUCCESS);
    }

    @Override
    public BaseResult delete(TagClassDTO reqDto) {
        TagClass old = tagClassDao.getById(reqDto.getClassId());
        if(old==null){
            throw new BaseException("标签不存在");
        }
        old.setClassStatus(TagClassStatusEnum.DELETE.getValue());
        old.setUpdateTime(LocalDateTime.now());
        tagClassDao.updateById(old);
        return BaseResult.success(ResultStatusEnum.SUCCESS);
    }

    public Integer getSortNo(Integer parentId, Integer level){
        Integer sortNo = tagClassDao.getSortNoByLevel(parentId,level);
        if(sortNo==null){
            sortNo=1;
        }else{
            sortNo+=1;
        }
        return sortNo;
    }

    public void paramValid(TagClassDTO reqDto, OperationTypeEnum typeEnum){
        if(OperationTypeEnum.ADD.equals(typeEnum)
                ||OperationTypeEnum.UPDATE.equals(typeEnum)){
            if(StringUtils.isBlank(reqDto.getClassName())){
                throw new BaseException("标签分类名称不能为空");
            }
            if(StringUtils.isBlank(reqDto.getClassDescription())){
                throw new BaseException("标签分类描述不能为空");
            }
            TagClass className = tagClassDao.getClassName(reqDto,typeEnum);
            if(className!=null){
                throw new BaseException("标签分类名称不能重复");
            }
        }
    }

    @Override
    public List<TagClass> getClass(TagClassDTO reqDto) {
        return tagClassDao.getClass(reqDto);
    }

    @Override
    public void export(TagClassPageDTO reqDto, HttpServletResponse response) {
        String fileName = "tagClassExport";
        String fileType = ".xlsx";
        int extCount = 0;
        reqDto.setPage(1);
        reqDto.setPageSize(1000);
        BasePage<TagClassVO> basePage = tagClassDao.pagelist(reqDto);
        List<TagClassVO> list = basePage.getList();
        List<TagClassVO> extList = new ArrayList<>();
        ExportParams params = new ExportParams(fileName + "导出时间：" + DateTimeUtil.formatYYYY_MM_DD_HH_MM_SS(LocalDateTime.now()) + "", "标签列表");
        params.setCreateHeadRows(true);
        IWriter<Workbook> workbookIWriter = ExcelExportUtil.exportBigExcel(params, TagClassVO.class);
        long total = basePage.getTotal();
        for (int i = 1; i <= 100; i++) {
            if (i != 1) {
                reqDto.setPage(i);
                basePage =tagClassDao.pagelist(reqDto);
            }
            list = basePage.getList();
            extCount += CollectionUtils.isEmpty(list) ? 0 : list.size();
            for (TagClassVO tempVo : list) {
                extList.add(tempVo);
            }
            list.clear();
            if (extCount >= total) {
                break;
            }
        }
        workbookIWriter.write(extList);
        Workbook workbook = workbookIWriter.get();
        if (workbook != null) {
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName + fileType, "UTF-8"));
                response.setHeader("Access-Control-Expose-Headers", "filename");
                response.setHeader("filename", java.net.URLEncoder.encode(fileName + fileType, "UTF-8"));
                workbook.write(outputStream);
            } catch (IOException e) {
                log.error("export tagclass 导出异常", e);
                throw new BaseException(ErrorCodeEnums.EXPORT_IS_ERROR);
            }
        }
    }
}
